<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Promise2(resolver) {
            let listener = null;
            let state = "pending";
            // publish
            const resolve = (val) => {
                if (listener && state === "pending") {
                    
                    // 限制 listener 只调用 1 次
                    listener(val);
                    state = "fulfilled";
                }
            };
            resolver(resolve);
            return {
                // subscribe
                then(cb) {
                    debugger
                    listener = cb;
                },
            };
        }
        // Promise2((res) => {
        //   console.log(1);
        //   res(2);
        //   console.log(3);
        // }).then((res) => {
        //   console.log(res);
        // });

        // Promise 语义：我承诺你1件事，一段时间以后给你答案
        new Promise2((res) => {
            console.log(1);
            res(2);
            console.log(3);
            // 2 必须要在 3 后面打印
        }).then(
            (res) => {
            // 132
            console.log(res);
        });
    </script>
</body>

</html>